package handler

import (
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"platform/internal/logic"
	"platform/internal/svc"
	"platform/internal/types"
	"platform/proto/plugin"
)

// PluginDispatcher 插件请求分发器
func PluginDispatcher(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var param types.PluginRequest
		err := httpx.Parse(r, &param)
		if err != nil {
			httpx.Error(w, httpError("无效的插件路径", http.StatusBadRequest))
			return
		}
		//// 提取插件名称，路径格式: /api/plugins/{plugin-name}/...
		//pathParts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
		//if len(pathParts) < 3 {
		//	httpx.Error(w, httpError("无效的插件路径", http.StatusBadRequest))
		//	return
		//}
		pluginName := param.Plugin
		pluginPath := "/" + param.Suffix

		// 从上下文获取用户信息
		userID, _ := r.Context().Value("userID").(string)
		// 读取请求体
		var body []byte
		if r.Body != nil {
			buf := make([]byte, r.ContentLength)
			_, err := r.Body.Read(buf)
			if err == nil {
				body = buf
			}
		}

		// 构建插件请求
		pluginReq := &plugin.Request{
			Method:  r.Method,
			Path:    pluginPath,
			Headers: make(map[string]string),
			Body:    body,
			UserId:  userID,
		}

		// 复制Headers
		for k, v := range r.Header {
			if len(v) > 0 {
				pluginReq.Headers[k] = v[0]
			}
		}

		l := logic.NewPluginLogic(r.Context(), svcCtx)
		resp, err := l.CallPlugin(pluginName, pluginReq)
		if err != nil {
			httpx.Error(w, httpError(err.Error(), http.StatusInternalServerError))
			return
		}

		// 设置响应Headers
		for k, v := range resp.Headers {
			w.Header().Set(k, v)
		}

		// 设置状态码和响应体
		w.WriteHeader(int(resp.StatusCode))
		w.Write(resp.Body)
	}
}

func httpError(msg string, code int) error {
	return &HttpError{
		Message: msg,
		Code:    code,
	}
}

type HttpError struct {
	Message string `json:"message"`
	Code    int    `json:"code"`
}

func (e *HttpError) Error() string {
	return e.Message
}
